package com.wwwzh.himalayafm.fragment.disfragment;


import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.wwwzh.himalayafm.R;
import com.wwwzh.himalayafm.adapter.category.CategoryRecyclerViewAdpter;
import com.wwwzh.himalayafm.adapter.category.CategoryViewPagerAdapter;
import com.wwwzh.himalayafm.entity.entity_category.BottomEntity;
import com.wwwzh.himalayafm.entity.entity_category.TotalEntity;
import com.wwwzh.himalayafm.retrofit.HttpService;

import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 * 分类界面碎片
 */
public class CategoryFragment extends Fragment implements ViewPager.OnPageChangeListener {

    private HttpService mService;
    private RecyclerView mRecyclerView;
    private CategoryRecyclerViewAdpter mRecyclerViewAdpter;
    private ViewPager mViewPager;
    private HttpService mBottomSerivce;
    private LinearLayout mLinearLayout;
    private List<ImageView> list;
    private Timer mTimer;
    private int index = 0;
    private DrawerLayout drawerLayout;
    private int mPosition;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);
        initViews(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        aboutRecyclerView();
        aboutViewPager();

    }

    /**
     * 关于ViewPager的操作
     */
    private void aboutViewPager() {
        //底部Viewpager的retotfit获取
        mBottomSerivce = new Retrofit.Builder()
                .baseUrl("http://adse.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(HttpService.class);
        mBottomSerivce.getBottomEntity("android", "cata_index_banner", "wifi", 0, "4.3.98")
                .enqueue(new Callback<BottomEntity>() {
                    @Override
                    public void onResponse(Call<BottomEntity> call, Response<BottomEntity> response) {
                        BottomEntity body = response.body();
                        //准备数据源
                        list = new LinkedList<ImageView>();
                        for (int i = 0; i < body.getData().size(); i++) {
                            ImageView imageView = new ImageView(getContext());
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                            Picasso.with(getContext()).load(body.getData().get(i).getCover()).into(imageView);
                            imageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(getContext(), "暂时无法跳转哦", Toast.LENGTH_SHORT).show();
                                }
                            });
                            list.add(imageView);
                            //根据图片个数 动态添加小圆点
                            ImageView dot = new ImageView(getContext());
                            dot.setPadding(10, 0, 10, 0);
                            dot.setImageResource(R.drawable.category_selector);
                            mLinearLayout.addView(dot);
                        }
                        ImageView imageView = new ImageView(getContext());
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        Picasso.with(getContext()).load(body.getData().get(0).getCover()).into(imageView);
                        list.add(imageView);

                        //准备适配器
                        CategoryViewPagerAdapter adapter = new CategoryViewPagerAdapter(list);
                        //绑定适配器
                        mViewPager.setAdapter(adapter);
                        //第一个圆点默认为选中
                        mLinearLayout.getChildAt(0).setSelected(true);
                        aboutCyclePager();
                    }

                    @Override
                    public void onFailure(Call<BottomEntity> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
        //给ViewPager添加页面滚动监听器
        mViewPager.addOnPageChangeListener(this);
    }

    /**
     * 有关RecyclerView的操作
     */
    private void aboutRecyclerView() {
        mRecyclerViewAdpter = new CategoryRecyclerViewAdpter(getContext());
        mRecyclerView.setAdapter(mRecyclerViewAdpter);
        aboutNetWorkDown();
        GridLayoutManager manager = new GridLayoutManager(getContext(), 2);//给定列数2
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0) {//如果是第一行，合并2列为一列
                    return 2;
                }
                return 1;
            }
        });
        mRecyclerView.setLayoutManager(manager);
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                if (parent.getChildAdapterPosition(view) % 6 == 0) {
                    outRect.set(0, 0, 0, 20);
                }
            }
        };
        mRecyclerView.addItemDecoration(decoration);
    }

    /**
     * 网络下载分类界面内容
     */
    private void aboutNetWorkDown() {
        mService = new Retrofit.Builder()
                .baseUrl("http://mobile.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(HttpService.class);
        mService.getCategoryEntity("and-a1", "android", 13, 2)
                .enqueue(new Callback<TotalEntity>() {
                    @Override
                    public void onResponse(Call<TotalEntity> call, Response<TotalEntity> response) {
                        TotalEntity body = response.body();
                        mRecyclerViewAdpter.addAll(body.getList());
                    }

                    @Override
                    public void onFailure(Call<TotalEntity> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    /**
     * 初始化控件实例
     *
     * @param view
     */
    private void initViews(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_category_id);
        mViewPager = (ViewPager) view.findViewById(R.id.vp_category_id);
        mLinearLayout = (LinearLayout) view.findViewById(R.id.ll_category_id);
    }

    /**
     * ViewPager自动循环播放图片
     */
    private void aboutCyclePager() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mViewPager.setCurrentItem(index++, false);
                        if (index == list.size()-1) {
                            index = 0;
                        }
                    }
                });
            }
        }, 0, 10 * 1000);

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        mPosition = position;
        //小圆点和ViewPager联动
        for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
            mLinearLayout.getChildAt(i).setSelected(i==position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (mPosition == list.size() - 1) {
                    mViewPager.setCurrentItem(0, false);
                }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
        }
    }
}

